<template>
  <div class="register-page">
    <div class="register-form-container">
      <el-card class="register-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h2>欢迎注册</h2>
            <p class="subtitle">创建您的账号</p>
          </div>
        </template>
        <el-form :model="registerForm" label-position="top" class="register-form">
          <el-form-item label="用户名">
            <el-input 
              v-model="registerForm.username" 
              placeholder="请输入您的用户名"
              prefix-icon="el-icon-user"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱地址">
            <el-input 
              v-model="registerForm.email" 
              placeholder="请输入您的邮箱地址"
              prefix-icon="el-icon-message"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input 
              type="password" 
              v-model="registerForm.password" 
              placeholder="请输入您的密码"
              prefix-icon="el-icon-lock"
              show-password
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input 
              type="password" 
              v-model="registerForm.password_confirm" 
              placeholder="请确认您的密码"
              prefix-icon="el-icon-lock"
              show-password
              :clearable="true"
            ></el-input>
          </el-form-item>
          <div class="form-actions">
            <el-button 
              type="primary" 
              @click="handleRegister" 
              class="register-button"
            >注册</el-button>
            <div class="secondary-actions">
              <el-button 
                text 
                @click="resetForm"
                class="reset-button"
              >重置</el-button>
              <el-button 
                type="success" 
                @click="router.push('/login')"
                class="login-button"
              >返回登录</el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

    <!-- 成功注册后弹出的对话框
    <el-dialog v-model="dialogVisible" :show-close="false" width="500">
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">This is a custom header!</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left">
                        <CircleCloseFilled />
                    </el-icon>
                    Close
                </el-button>
            </div>
        </template>
        This is dialog content.
    </el-dialog> -->
<!-- </template> -->

<script setup>
import { PostRegister } from '@/api/auth';
import { ref, nextTick, onMounted } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import router from '@/router';
console.log('register.vue');

// 表单模型
const registerForm = ref({
    username: '',
    email: '',
    password: '',
    password_confirm: ''
});

// 对话框显示控制
const dialogVisible = ref(false);

// 处理表单提交
const handleRegister = async () => {
    try {
        await nextTick();
        const response = await PostRegister(registerForm.value);
        const { code, msg, errors } = response.data;

        // 如果注册成功
        if (code === 200) {
            ElMessage.success(msg);  // 注册成功提示
            // dialogVisible.value = true;  // 显示对话框


            ElMessageBox.confirm(
                '注册成功，是否现在去登录?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            ).then(() => {
                // 用户点击确定后的操作，例如导航到首页或其他页面
                router.push('/login'); // 假设首页路径为 '/'
            }).catch(() => {
                // 用户点击取消后的操作（如果需要）
                ElMessage({
                    type: 'info',
                    message: '已取消跳转'
                });
            });


        } else if (code === 400) {
            // 如果是400错误，显示后端返回的具体错误信息
            if (errors) {
                for (const [field, errorMsg] of Object.entries(errors)) {
                    ElMessage.error(`${field}: ${errorMsg}`);  // 显示字段名和错误信息
                }
            } else {
                ElMessage.error(msg || 'Registration failed');
            }
        }
    } catch (error) {
        console.error('Error:', error);
        if (error.response && error.response.data) {
            const { code, errors } = error.response.data;
            if (code === 400 && errors) {
                for (const [field, errorMsg] of Object.entries(errors)) {
                    ElMessage.error(`${field}: ${errorMsg}`);
                }
            } else {
                ElMessage.error('An error occurred during registration.');
            }
        } else {
            ElMessage.error('Server error. Please try again later.');
        }
    }
};

// 重置表单
const resetForm = () => {
    registerForm.value = {
        username: '',
        email: '',
        password: '',
        password_confirm: ''
    };
};

// 跳转到登录页面
const redirectToLogin = () => {
    router.push('/login');
};


const checkLogin = () => {
    // 检查是否已经登录
    const user_info = localStorage.getItem('user_info');
    if (user_info) {
        // 已经登录，跳转到首页
        router.push('/');
        ElMessage.warning('您已登录');
    }
};

onMounted(() => {
    // 初始化表单数据
    checkLogin();
});

</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.register-form-container {
  width: 100%;
  max-width: 420px;
  margin: auto;
}

.register-card {
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.register-card:hover {
  transform: translateY(-5px);
}

.card-header {
  text-align: center;
  padding: 0 0 20px;
}

.card-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.subtitle {
  margin: 10px 0 0;
  color: #7f8c8d;
  font-size: 14px;
}

.register-form {
  padding: 20px 10px;
}

.form-actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.register-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
  background: linear-gradient(45deg, #4CAF50, #45a049);
  border: none;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
}

.secondary-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reset-button {
  color: #95a5a6;
  transition: color 0.3s ease;
}

.reset-button:hover {
  color: #7f8c8d;
}

.login-button {
  background: transparent;
  border: 2px solid #4CAF50;
  color: #4CAF50;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: #4CAF50;
  color: white;
}

:deep(.el-input__wrapper) {
  border-radius: 20px;
  padding: 0 15px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #34495e;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>
